<!-- brand list select -->
<template>
  <el-select class="brand-select" v-model="values" filterable clearable remote reserve-keyword :placeholder="placeholder"
             :remote-method="remoteMethod" :loading="loading" @change="handleChange">
    <el-option v-for="item in options" :key="item.value" :value="item.value" :label="item.name">
      <img :src="item.logo" alt="">
      <span>{{item.name}}</span>
    </el-option>
  </el-select>
</template>

<script>
import { GetBrandListAll } from '@/api/onlineMan'
export default {
  name: 'brandListSelect',
  data () {
    return {
      values: [],
      loading: false,
      options: [],
      list: []
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择场所'
    },
    returnIdName: {
      type: String,
      // name id idname
      default: 'name'
    }
  },
  created () {
    this.getList()
  },
  watch: {
    'value': function (val) {
      this.values = val
      this.handleChange(val)
    }
  },
  mounted () {
    this.values = this.value
  },
  methods: {
    getList () {
      GetBrandListAll().then(res => {
        const data = res.data
        if (data && data.length > 0) {
          data.forEach(item => {
            item.value = item.id.toString()
          })
        }
        this.values = this.value
        this.options = this.list = data
      }).catch(() => {
      })
    },
    remoteMethod (query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.options = this.list.filter(item => {
            return item.name.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.options = this.list
      }
    },
    handleChange (value) {
      let item = []
      let name = ''
      if (value) {
        item = this.options.filter(item => {
          return item.value === value
        })
        name = item[0] ? item[0].name : ''
      }

      if (this.returnIdName === 'name') {
        this.$emit('getBrandName', name)
      } else if (this.returnIdName === 'id') {
        this.$emit('input', value)
      } else {
        this.$emit('input', value)
        this.$emit('getBrandName', name)
      }
    }
  }

}

</script>
